library(data.table)

# t <- data.frame(
#   Type = c("Prior", "Likelihood", "Posterior"),
#   Mean = c(18.0, 17.2, 3),
#   Standard_Dev = c(1.56, 0.89, 3),
#   Precision = numeric(length=3)
# )


t2 <- data.table(
  Type = c("Prior", "Likelihood", "Posterior"),
  Mean = c(18.0, 17.2, NA_real_),
  Standard_Dev = c(1.56, 0.89, NA_real_),
  Precision = numeric(length = 3)
)


cal_fc <- function(d) {
  d$Precision <- 1 / (d$Standard_Dev ** 2)
  mt <- sum(d$Precision[d$Type != 'Posterior'])
  d$Precision[d$Type == 'Posterior'] <- mt
  d$Standard_Dev[d$Type == 'Posterior'] <- sqrt(1 / mt)
  d$Mean[d$Type == 'Posterior'] <- sum(d$Precision[d$Type != 'Posterior'] * d$Mean[d$Type != 'Posterior']) / mt
  
  d
}

t2 <- cal_fc(t2)

setcolorder(t2, c("Type", "Mean", "Precision", "Standard_Dev"))

t2 <- t2 %>%
  mutate(across(c(Mean, Standard_Dev, Precision), ~ round(.x, 2)))


observed_data <- c(
  15.1,
  11.8,
  21.0,
  22.7,
  18.6,
  16.2,
  11.1,
  13.2,
  20.4,
  19.2,
  21.2,
  14.3,
  18.6,
  16.8,
  20.3,
  19.9,
  15.0,
  13.4,
  19.9,
  15.3
)

mean(observed_data)

sd(observed_data)


 4/sqrt(20)
#
1 / (4/sqrt(20))**2
# 20 / 4**2
#
# 1/ 0.8944272 ** 2
#
 1 / (0.89 ** 2)


mu_0 <- 18.0
sigma_0 <- 1.56
precision_0 <- 1 / (sigma_0 ** 2)

n <- 20
sigma_n <- 4 / sqrt(n)
precision_n <- 1 / (sigma_n ** 2)

mu_n <- (precision_0 * mu_0 + precision_n * mean(observed_data) * n) / (precision_0 + n* precision_n)
sigma_n <- sqrt(1/(precision_0 + precision_n))

qnorm(c(0.05, 0.95), 17.4, 0.77)

normal.select(list(p=0.5, x=18), list(p=0.90, x=20))

